<template>
  <div v-clickoutside="closeMenu" :style="{'paddingLeft': paddingLeft, 'height': height}" :class="{'mobile-tab tab-padding': showMobilePage && isTable}" class="list-tab">
    <div class="table-list-tabs-content">
      <slot name="head"/>
      <ModeSwitch v-if="modeList && modeList.length" :mode="mode" :mode-list="modeList" />
      <div :class="[{ 'isCenter': isCenter },{'showNextBtn':showNextBtn},{'is-scrollable':scrollable},{'is-drop-scrollable': scrollable && showDrop},{'not-scrollable': !showScrollable},{'pl8': showScrollable}]" class="table-list-tabs-content-flex">
        <template v-if="scrollable || showMenu">
          <span v-if="showNextBtn" :class="['fb-tabs__nav-prev', scrollable.prev ? '' : 'is-disabled']" @click="scrollPrev"><i class="el-icon-arrow-left"/></span>
          <span v-if="showNextBtn" :class="['fb-tabs__nav-next', scrollable.next ? '' : 'is-disabled']" @click="scrollNext"><i class="el-icon-arrow-right"/></span>
          <div v-if="showDrop && (scrollable || showMenu)" class="fb-tavs__nav-drop-container">
            <div :style="{'font-size': fontSize}" title="展示全部" class="fb-tavs__nav-drop" @click="switchDrop(true)">
              <span>{{ showMenu ? '收起' : '更多' }}</span>
              <i :class="[{'el-icon-arrow-down': !showMenu},{'el-icon-arrow-up': showMenu}]"/>
            </div>
          </div>

        </template>
        <div ref="listTabScroll" :class="[showMobilePage && isTable ?'mobile-tab-scroll' : 'tab-scroll']">
          <div ref="navRef" :style="navStyle" class="table-list-tabs-content-nav">
            <template v-if="!showMenu">
              <template v-for="item in tabs">
                <div
                  v-if="!item.isHidden"
                  :key="item[idName]"
                  :ref="`item_${item[idName]}`"
                  :class="['table-list-tabs-item', curIndex === item[idName] ? 'active' : '']"
                  @click="handleClick(item[idName])"
                >
                  <el-tooltip v-if="item[keyName].length > 18" :open-delay="800" placement="top" effect="dark">
                    <div slot="content" style="max-width:300px">{{ item[keyName] }}</div>
                    <el-badge :is-dot="item.isDot" :style="{'font-size': fontSize}" :class="{'mobile-item-content': showMobilePage}" class="item-content">{{ handleName(item[keyName]) }}</el-badge>
                  </el-tooltip>
                  <el-badge v-else :is-dot="item.isDot" :style="{'font-size': fontSize}" :class="{'mobile-item-content': showMobilePage}" class="item-content">{{ item[keyName] }}</el-badge>
                  <div v-if="((showZero && (item.num || item.num === 0)) || (!showZero && item.num && item.num > 0)) && !(noShowNumArray.indexOf(item[idName]) >= 0)" :class="{'r15':item.num > 9, 'r20': item.num > 99, 'r25': item.num > 999}" class="item-badge">{{ item.num >= maxBadge.num ? maxBadge.str : item.num }}{{ item.num > maxBadge.num && maxBadge.unit?maxBadge.unit:'' }}</div>
                  <div v-if="item.dotColor" :style="{backgroundColor: item.dotColor}" class="dot" />
                  <i v-if="showDelete && !item.disabledDel" class="el-icon-close close-icon" @click.stop="$emit('deleteTab', item)"/>
                </div>
              </template>
              <slot name="extendTabs" />
            </template>
            <div v-else-if="!showMobilePage" :style="{'font-size': fontSize+'!important'}" class="item-title">全部分类</div>
          </div>
        </div>
      </div>
      <div style="flex:1;"/>
      <slot />
      <div v-if="showHeader">
        <ListHeader />
      </div>
    </div>
    <PureTab :show-header="showHeader" :height="height" v-model="curIndex" :tabs="tabs" :show-menu.sync="showMenu" :max-height="pureTabMaxHeight" :font-size="fontSize" :key-name="keyName" :id-name="idName" @handleTabClick="handleClick" />
  </div>
</template>
<script>
import ListHeader from '@/components/Common/header/listHeader';
import Clickoutside from 'element-ui/src/utils/clickoutside';
import ModeSwitch from './modeSwitch';
import PureTab from './pureTab';
import { mapState } from 'vuex';

export default {
  name: 'ListTab',
  components: { ListHeader, PureTab, ModeSwitch },
  directives: { Clickoutside },
  model: {
    prop: 'curIndex',
    event: 'tabClick'
  },
  props: {
    tabs: {
      type: Array,
      default: () => []
    },
    height: {
      type: String,
      default: '48px'
    },
    curIndex: {
      type: Number | String,
      default: 1
    },
    paddingLeft: {
      type: String,
      default: '32px'
    },
    isCenter: {
      type: Boolean,
      default: false
    },
    noShowNumArray: { // 用来定义不需要显示数量的tag
      type: Array,
      default: () => [-1]
    },
    showHeader: {
      type: Boolean,
      default: false
    },
    showDrop: { // 开启下拉展示全部
      type: Boolean,
      default: false
    },
    showZero: {
      type: Boolean,
      default: false
    },
    isSelfTab: { // 是否只能通过父组件修改 tab id
      type: Boolean,
      default: false
    },
    showDelete: { // 是否开启删除功能
      type: Boolean,
      default: false
    },
    showScrollable: { // 是否可显示滚动
      type: Boolean,
      default: true
    },
    pureTabMaxHeight: { // 显示更多最大高度
      type: String,
      default: 'none'
    },
    /** maxBadge:
     * num: 最大值
     * str: 大于等于最大值时显示这个文案
     * unit: 大于最大值时在文案后面增加这个单位
     */
    maxBadge: {
      type: Object,
      default() {
        return {
          num: 10000,
          str: '1w',
          unit: '+'
        };
      }
    },
    fontSize: {
      type: String,
      default: '14px'
    },
    isTable: {// 是否列表页
      type: Boolean,
      default: false
    },
    mode: {
      type: Number,
      default: null
    },
    modeList: {
      type: Array,
      default: () => ([])
    },
    keyName: { // 取值的key
      type: String,
      default: 'name'
    },
    idName: { // 取值的key
      type: String,
      default: 'id'
    }
  },
  data() {
    return {
      navOffset: 0,
      scrollable: false,
      showMenu: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    }),
    navStyle() {
      return {
        transform: `translateX(-${this.navOffset}px)`
      };
    },
    showNextBtn() {
      return this.scrollable && this.showScrollable && !this.showMobilePage;
    }
  },
  updated() {
    this.update();
  },
  mounted() {
    window.addEventListener('resize', this.update);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.update);
  },
  methods: {
    handleName(str = '') {
      if (!str) { return ''; }
      if (str.length > 18) {
        return str.slice(0, 18) + '...';
      }
      return str;
    },
    handleClick(id) {
      if (this.showMobilePage && this.isTable) {
        let target = {};// 点击的元素
        if (Array.isArray(this.$refs[`item_${id}`])) {
          target = this.$refs[`item_${id}`][0];
        } else {
          target = this.$refs[`item_${id}`];
        }
        // 判断点击元素是否超过一半
        const width = window.innerWidth / 2; // 一半屏幕宽度
        const leftW = (target.offsetWidth / 2) + target.offsetLeft; // 点击元素中点距离屏幕左侧
        if (leftW > width) {
          this.$refs.listTabScroll.scrollLeft = leftW - width;// 滚动到中间
        } else {
          this.$refs.listTabScroll.scrollLeft = 0; // 滚动到最前
        }
      }
      if (!this.isSelfTab) {
        this.$emit('tabClick', id);
      } else {
        this.$emit('handleTabClick', id);
      }
      this.$nextTick(() => {
        this.closeMenu();
      });
    },
    scrollPrev() {
      const containerSize = this.$refs.listTabScroll['offsetWidth'];
      const currentOffset = this.navOffset;
      if (!currentOffset) return;

      const newOffset = currentOffset > containerSize
        ? currentOffset - containerSize
        : 0;

      this.navOffset = newOffset;
    },
    scrollNext() {
      const navSize = this.$refs.navRef['offsetWidth'];
      const containerSize = this.$refs.listTabScroll['offsetWidth'];
      const currentOffset = this.navOffset;

      if (navSize - currentOffset <= containerSize) return;

      const newOffset = navSize - currentOffset > containerSize * 2
        ? currentOffset + containerSize
        : (navSize - containerSize);

      this.navOffset = newOffset;
    },
    update() {
      if (this.$refs.listTabScroll && this.$refs.navRef) {
        const containerSize = this.$refs.listTabScroll['offsetWidth'];
        const navSize = this.$refs.navRef['offsetWidth'];

        const currentOffset = this.navOffset;

        if (containerSize < navSize) {
          this.scrollable = this.scrollable || {};
          this.scrollable.prev = currentOffset;
          this.scrollable.next = currentOffset + containerSize < navSize;
          if (navSize - currentOffset < containerSize) {
            this.navOffset = navSize - containerSize;
          }
        } else {
          this.scrollable = false;
          if (currentOffset > 0) {
            this.navOffset = 0;
          }
        }
      }
    },
    switchDrop() {
      this.showMenu = !this.showMenu;
    },
    closeMenu(flag) {
      if (!this.showDrop) return;
      this.showMenu = false;
    }
  }
};
</script>
<style lang="scss" scoped>
.mobile-tab {
  box-shadow: 2px 4px 5px 0 rgba(221,225,234,0.3);
  padding: 0 !important;
}
.tab-padding {
  .table-list-tabs-content-flex {
    padding: 0 0 0 16px !important;
  }
}
// 列表中的tab切换样式
.list-tab {
  width: 100%;
  background-color: #fff;
  // padding-left:32px;
  padding-right: 16px;
  position: relative;
  .table-list-tabs-header {
    position: relative;
  }
  .fb-tabs__nav-prev,.fb-tabs__nav-next,.fb-tavs__nav-drop-container {
    position: absolute;
    cursor: pointer;
    font-size: 12px;
    color: #909399;
    height: 100%;
    display: flex;
    align-items: center;
    z-index: 10;
  }
  .fb-tavs__nav-drop-container {
    right: 0;
    height: 100%;
  }
  .fb-tabs__nav-prev {
    left: 0;
  }
  .fb-tabs__nav-next {
    right: 0;
  }
  .fb-tavs__nav-drop {
    height: 32px;
    display: flex;
    align-items: center;
    right: 0;
    font-size: 14px;
    padding: 0 5px;
    color: #0D1F58;
    font-weight: bold;
    border-radius: 4px;
    &:hover {
      background-color: #EDEEF2;
    }
    > i {
      font-weight: bold;
    }
  }
  .item-badge {
    position: absolute;
    top: 5px;
    right: -9px;
    padding: 0 6px;
    height: 18px;
    min-width: 18px;
    line-height: 18px;
    text-align: center;
    border-radius: 10px;
    background-color: #FB5227;
    font-size: 12px;
    display: inline-block;
    color: #fff;
    transform: scale(0.9);
    margin-left: 4px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 500;
  }
  .r15 {
    right: -15px;
  }
  .r20 {
    right: -20px;
  }
  .r25 {
    right: -25px;
  }
  .table-list-tabs-content {
    width: 100%;
    height: 100%;
    box-sizing: border-box;
    margin: 0 auto;
    display: flex;
    .table-list-tabs-content-flex {
      overflow: hidden;
      position: relative;
      width: 100%;
      &.is-scrollable {
        padding: 0 20px;
        box-sizing: border-box;
      }
      &.is-drop-scrollable {
        padding: 0 70px 0 20px;
        .fb-tabs__nav-next {
          right: 56px !important;
        }
      }
      &.pl8 {
        padding-left: 8px;
      }
      &.not-scrollable {
        padding-left: 0 !important;
      }
      &.isCenter {
        justify-content: center;
      }
      .table-list-tabs-content-nav {
        white-space: nowrap;
        position: relative;
        transition: transform .3s;
        display: flex;
        float: left;
        height: 100%;
      }
    }
    .table-list-tabs-item {
      height: 100%;
      position: relative;
      margin: 0 16px;
      cursor: pointer;
      font-size: 16px;
      color:#333333;
      white-space: nowrap;
      font-weight:300;
      font-family: PingFangSC-Light, PingFang SC;
      display: flex;
      align-items: center;
      padding-right: 3px;
      .item-content {
        padding: 15px 0px;
        line-height: 1.15;
        display: flex;
        align-items: center;
      }
      .mobile-item-content {
        padding: 13px 0 10px;
      }
      &::v-deep {
        .is-dot {
          top: 15px;
        }
      }
      &:first-child {
        margin-left: 0;
      }
      &:last-child {
        margin-right: 0;
      }
      &.active {
        .item-content {
          position: relative;
          color: var(--color-primary);
          font-weight: bold;
          font-family:PingFangSC-Medium,PingFang SC;
          &::after{
            content: '';
            position: absolute;
            bottom: 0;
            left: 50%;
            border-radius: 4px;
            background-color: var(--color-primary);
            // width:40px;
            width: 100%;
            height:2px;
            transform: translateX(-50%);
            // margin-left: -20px;
          }
        }

      }
    }
    .showNextBtn {
      .table-list-tabs-item {
        &:first-child {
          margin-left: 12px;
        }
        &:last-child {
          margin-right: 12px;
        }
      }
    }
  }
}
.dot {
  width: 6px;
  height: 6px;
  margin-left: 2px;
  border-radius: 100%;
  position: relative;
  top: -4px;
}
.close-icon {
  margin-left: 4px;
  font-size: 13px;
}
.list-img {
  width: 16px;
  margin-right: 5px;
}
.item-title {
  font-size: 16px;
  color:#333333;
  white-space: nowrap;
  font-weight:300;
  display: flex;
  align-items: center;
  height: 100%;
  font-family: PingFangSC-Light, PingFang SC;
}
.tab-scroll {
  overflow:hidden;
  height: 100% ;
}
.mobile-tab-scroll {
  height: 100%;
  @include scrollBar($x: auto, $y: hidden, $thumbColor: transparent, $width: 0px);
  .table-list-tabs-item {
    .item-content {
      line-height: unset !important;
      font-weight: bold;
      &::after {
        bottom: -2px !important;
      }
    }
  }
}
</style>
